//
//  BrowseResultViewController.m
//  VoiceClass
//
//  Created by caoxiaobo on 2018/1/7.
//  Copyright © 2018年 YRX. All rights reserved.
//

#import "BrowseResultViewController.h"
#import "UIScrollView+TTWholeCapture.h"
#import "IAMetaDataReader.h"
#import "IAStudent.h"
#import "IASubjectItem.h"
#import "UIView+Extension.h"
#import "MBProgressHUD.h"
#import "Definition.h"
#import "IABrowseResultCell.h"
#import <UMengUShare/UShareUI/UMSocialUIManager.h>

#import <Photos/Photos.h>

static NSString * const browseResultCellID = @"browseResultCellID ";

typedef NS_ENUM(NSUInteger, BrowseSourceTag) {
    BrowseSourceTagStudent = 1001,
    BrowseSourceTagSubject,
    BrowseSourceTagAll,
};

@interface BrowseResultViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString *subjectName;
@property (nonatomic, strong) IAStudent *student;
@property (nonatomic, strong) NSArray <IABrowseResultItem *> *results;
@property (nonatomic, strong) UILabel *msgLabel;

@property (nonatomic, assign) BrowseSourceTag sourceTag;

@end

@implementation BrowseResultViewController

- (instancetype)initWithStudent:(IAStudent *)student {
    self = [super init];
    if (self) {
        _student = student;
        _sourceTag = BrowseSourceTagStudent;
    }
    return self;
}

- (instancetype)initWithSubjectName:(NSString *)name {
    self = [super init];
    if (self) {
        _subjectName = name;
        _sourceTag = BrowseSourceTagSubject;
    }
    return self;
}

- (instancetype)initWithSubjectResults:(NSArray <IASubjectAnswerResult *> *)results {
    self = [super init];
    if (self) {
        _results = [self resultItemFromResult:results];
        _sourceTag = BrowseSourceTagAll;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    switch (self.sourceTag) {
        case BrowseSourceTagSubject: {
            self.title = [NSString stringWithFormat:@"%@课程答题汇总", self.subjectName];
            [IAMetaDataReader getSubjectResultsForName:self.subjectName completion:^(id obj) {
                self.results = [self resultItemFromResult:obj];;
                self.navigationItem.rightBarButtonItem.enabled = self.results.count > 0;
                [self.tableView reloadData];
            }];
            break;
        }
        case BrowseSourceTagStudent: {
            self.title = [NSString stringWithFormat:@"%@的答题汇总", self.student.name];
            [IAMetaDataReader getSubjectResultsForStudent:self.student.stuID completion:^(id obj) {
                self.results = [self resultItemFromResult:obj];;
                self.navigationItem.rightBarButtonItem.enabled = self.results.count > 0;
                [self.tableView reloadData];
            }];
            break;
        }
        case BrowseSourceTagAll: {
            self.title = @"全部答题汇总";
            [IAMetaDataReader getAllSubjectResultsWithCompletion:^(id obj) {
                self.results = [self resultItemFromResult:obj];
                self.navigationItem.rightBarButtonItem.enabled = self.results.count > 0;
                [self.tableView reloadData];
            }];
            break;
        }
            
        default:
            break;
    }
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"更多" style:UIBarButtonItemStylePlain target:self action:@selector(showFunctionPanel)];
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    _tableView = [[UITableView alloc] init];
    _tableView.frame = self.view.bounds;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = CMNormalBg;
    [_tableView registerClass:[IABrowseResultCell class] forCellReuseIdentifier:browseResultCellID];
    [self.view addSubview:_tableView];
}

- (NSArray *)resultItemFromResult:(NSArray *)result {
    NSMutableArray *mutableArray = [NSMutableArray array];
    [result enumerateObjectsUsingBlock:^(IASubjectAnswerResult *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        IABrowseResultItem *item = [[IABrowseResultItem alloc] init];
        item.result = obj;
        [mutableArray addObject:item];
    }];
    return mutableArray;
}

- (void)showMsgHud:(NSString *)msg {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = msg;
    hud.mode = MBProgressHUDModeText;
    [hud hideAnimated:YES afterDelay:1.0];
}

- (void)showFunctionPanel {
    UMSocialShareUIConfig *uiconfig = [UMSocialShareUIConfig shareInstance];
    uiconfig.shareTitleViewConfig.shareTitleViewTitleString = @"请选择分享或导出";
    uiconfig.shareCancelControlConfig.shareCancelControlText = @"取消操作";
    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_WechatSession
                                     withPlatformIcon:[UIImage imageNamed:@"icon_share_wechat"]
                                     withPlatformName:@"微信好友"];
    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_QQ
                                     withPlatformIcon:[UIImage imageNamed:@"icon_share_qq"]
                                     withPlatformName:@"QQ好友"];
    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_Sina
                                     withPlatformIcon:[UIImage imageNamed:@"icon_share_copy"]
                                     withPlatformName:@"导出为图片"];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        if (platformType == UMSocialPlatformType_Sina) {
            [self save];
        } else {
            NSLog(@"userInfo");
        }
    }];
}

- (void)save {
    UIImage *image = [self.tableView ia_scrollViewCapture];
    if (!image) {
        // 错误弹框
        [self showMsgHud:@"转换图片格式失败"];
        return;
    }
    
    // 获取授权
    [self requestPhotoPermissionWithMessage:@"" doNext:^{
        __block NSString *localidentifier = nil;
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetChangeRequest *assetsRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
            localidentifier = assetsRequest.placeholderForCreatedAsset.localIdentifier;
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                PHFetchResult *assetResult = nil;
                if (localidentifier) {
                    assetResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[localidentifier] options:nil];
                }
                if (assetResult && assetResult.count > 0) {
                    [self showMsgHud:@"保存成功"];
                } else {
                    [self showMsgHud:@"保存失败"];
                }
            });
        }];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = self.results.count;
    if (count == 0) {
        [tableView addSubview:self.msgLabel];
    } else {
        [self.msgLabel removeFromSuperview];
    }
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IABrowseResultCell *cell = [tableView dequeueReusableCellWithIdentifier:browseResultCellID];
    if (!cell) {
        cell = [[IABrowseResultCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:browseResultCellID];
    }
    
    IABrowseResultItem *item = self.results[indexPath.row];
    cell.item = item;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    IABrowseResultItem *item = self.results[indexPath.row];
    return item.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UILabel *)msgLabel {
    if (!_msgLabel) {
        _msgLabel = [[UILabel alloc] init];
        _msgLabel.text = @"暂时还没有答题";
        _msgLabel.frame = CGRectMake(0, 0, self.tableView.cWidth, self.tableView.cHeight * 0.6);
        _msgLabel.font = [UIFont boldSystemFontOfSize:18.0f];
        _msgLabel.textColor = [UIColor lightGrayColor];
        _msgLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _msgLabel;
}

- (void)requestPhotoPermissionWithMessage:(NSString *)message doNext:(void (^)(void))doNext
{
    if (doNext == nil) { return; }
    
    if (message.length == 0) {
        message = @"请允许访问您的相册";
    }
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted ||
        status == PHAuthorizationStatusDenied) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                                 message:message
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
#pragma clang diagnostic pop
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                                                            style:UIAlertActionStyleDefault
                                                          handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    }
    
    if (status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if(status == PHAuthorizationStatusAuthorized) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    doNext();
                });
            }
        }];
        return;
    }
    
    if (status == PHAuthorizationStatusAuthorized) {
        doNext();
    }
}

@end
